import EssayCommentCard from '@/components/EssayCommentCard';
import MyCard from '@/components/MyCard';
import MyPageContainer from '@/components/MyPageContainer';
import CardList from '@/pages/bisheProject/components/CardList';
import {
  doBisheProjectClickUsingGet,
  getBisheProjectVoByIdUsingGet,
  listBisheProjectVoByPageUsingPost,
} from '@/services/backend/bisheProjectController';
import { addOrderInfoUsingPost } from '@/services/backend/orderInfoController';
import { createFromIconfontCN } from '@ant-design/icons';
import { history, useRequest } from '@umijs/max';
import { Button, Card, Checkbox, Col, Flex, Form, message, Row, Tag, Typography } from 'antd';
import { FormProps } from 'antd/lib';
import { MdCatalog, MdPreview } from 'md-editor-rt';
import { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import useStyles from './style.style';

//等待时间
const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

//价格转换(分->元)
const switchFenToYuan = (val: number | undefined) => {
  if (val === undefined || val === null || val < 0) {
    return 0;
  }
  return val / 100;
};

interface PayChoiceProps {
  bisheProjectVO: API.BisheProjectVO;
}

//支付node
const PayChoice: React.FC<PayChoiceProps> = (props) => {
  const { bisheProjectVO } = props;
  const [total, setTotal] = useState<number>(0);
  const [submitLoading, setSubmitLoading] = useState<boolean>(false);
  // 添加选中状态的记录
  const [selectedItems, setSelectedItems] = useState<{
    needCode: number;
    needDoc: number;
    needDeploy: number;
  }>({
    needCode: 0,
    needDoc: 0,
    needDeploy: 0,
  });

  type FieldType = {
    payGroup?: number[];
    protocol?: string;
  };

  /**
   * 处理订单支付
   * @param bisheProjectVO
   * @param payGroup
   */
  const handleOrder = async (bisheProjectVO: API.BisheProjectVO) => {
    setSubmitLoading(true);
    try {
      const res = await addOrderInfoUsingPost({
        name: bisheProjectVO.title,
        targetId: bisheProjectVO.id,
        type: 'project',
        ...selectedItems,
      });
      if (res.code === 0 && res.data) {
        message.success('下单成功,3s后跳转~');
        await waitTime(3000);
        history.replace(`/bisheProject/order/${res.data}`);
      }
    } catch (e: any) {
      message.error(e.message);
    } finally {
      setSubmitLoading(false);
    }
  };

  const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
    const { payGroup, protocol } = values;
    if (!protocol) {
      message.error('请阅读平台用户协议、购买协议和隐私政策后勾选同意');
      return;
    }
    if (payGroup?.length === 0) {
      message.warning('您还未勾选任何选项');
      return;
    }
    // 将选中状态和价格一起传递给处理函数
    handleOrder(bisheProjectVO).then(() => {});
  };

  return (
    <div>
      <Typography.Title level={4} type={'danger'}>
        请选择你要下单的服务
      </Typography.Title>
      <Form name="basic" onFinish={onFinish} initialValues={{ payGroup: [] }} autoComplete="off">
        <Form.Item<FieldType> name="payGroup">
          <Checkbox.Group
            onChange={(checkedValue) => {
              if (checkedValue.length === 0) {
                setTotal(0);
                setSelectedItems({
                  needCode: 0,
                  needDoc: 0,
                  needDeploy: 0,
                });
                return;
              }

              // 计算总价
              let newTotal = 0;
              // 遍历选中的值，计算总价
              checkedValue.forEach((item) => {
                if (item === 'needCode') {
                  newTotal += switchFenToYuan(bisheProjectVO.codePrice);
                } else if (item === 'needDoc') {
                  newTotal += switchFenToYuan(bisheProjectVO.docPrice);
                } else if (item === 'needDeploy') {
                  newTotal += 50; // 远程部署服务固定价格
                }
              });
              setTotal(newTotal);

              // 更新选中状态
              const newSelectedItems = {
                needCode: 0,
                needDoc: 0,
                needDeploy: 0,
              };
              // 遍历选中的值，设置对应的属性为1
              checkedValue.forEach((item) => {
                // @ts-ignore
                newSelectedItems[item] = 1;
              });
              setSelectedItems(newSelectedItems);
            }}
          >
            <Row>
              <Col span={24}>
                <Checkbox value={'needCode'} style={{ lineHeight: '32px' }}>
                  项目代码 + 数据库SQL
                </Checkbox>
              </Col>
              <Col span={24}>
                <Checkbox value={'needDoc'} style={{ lineHeight: '32px' }}>
                  项目资料（用例图、用例表、流程图、数据库表设计、E-R图等）
                </Checkbox>
              </Col>
              <Col span={24}>
                <Checkbox value={'needDeploy'} style={{ lineHeight: '32px' }}>
                  远程部署调试服务（联系方式下单后可见）
                </Checkbox>
              </Col>
            </Row>
          </Checkbox.Group>
        </Form.Item>
        <Typography.Title level={4}>
          总费用：<span className={'text-[#ff4d4f]'}>￥{total}</span>
        </Typography.Title>

        <Flex justify={'center'} className={'mb-1.5'}>
          <Form.Item<FieldType>
            name="protocol"
            valuePropName="checked"
            noStyle={true}
            className={'mb-1.5'}
            label={null}
          >
            <Checkbox>
              我已阅读并同意平台
              <Typography.Link>用户协议</Typography.Link>、
              <Typography.Link>购买协议</Typography.Link>和
              <Typography.Link>隐私政策</Typography.Link>
            </Checkbox>
          </Form.Item>
        </Flex>
        <Flex justify={'center'}>
          <Form.Item label={null} noStyle={true}>
            <Button type={'primary'} htmlType="submit" block={true} loading={submitLoading}>
              下单
            </Button>
          </Form.Item>
        </Flex>
      </Form>
    </div>
  );
};

const tagColorList = ['processing', 'success', 'error', 'warning'];

const MyIcon = createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/c/font_4870840_ehrofciuqz.js', // 在 iconfont.cn 上生成
});

const Detail: React.FC = () => {
  const { styles } = useStyles();
  const params = useParams();
  const id = (params['id'] ?? -1) as number;
  const scrollElement = document.documentElement;

  const [hotBisheProjects, setHotBisheProjects] = useState<API.BisheProjectVO[]>([]);

  const { data, loading } = useRequest(() => {
    return getBisheProjectVoByIdUsingGet({ id });
  });

  //获取最热门的前5个项目
  const loadHotBisheProject = async () => {
    const res = await listBisheProjectVoByPageUsingPost({
      sortField: 'clickNum',
      sortOrder: 'descend',
    });
    if (res.code === 0) {
      setHotBisheProjects(res.data?.records?.slice(0, 5) ?? []);
    }
  };

  //初始化页面
  useEffect(() => {
    //浏览数+1
    doBisheProjectClickUsingGet({ bisheProjectId: id });
    loadHotBisheProject();
  }, []);

  //标签node
  const tagNode: React.ReactNode = data?.tagList?.map((tag, index) => {
    return (
      <Tag
        key={index}
        bordered={false}
        color={tagColorList[index % 4]}
        style={{ fontSize: '16px', lineHeight: '34px' }}
      >
        {tag}
      </Tag>
    );
  });

  //内容node
  const content: React.ReactNode = (
    <>
      <div className={styles.head}>
        <div className={styles.detailTitle}> {data?.title}</div>
        <div className={styles.detailDescription}> {data?.subtitle}</div>
        <Flex gap="4px 0" wrap style={{ margin: '16px 0' }}>
          {tagNode}
        </Flex>
        <div className={'flex items-center gap-2 text-base text-[#1c1f21] mt-5 mb-5'}>
          👉功能演示地址:
          <Typography.Link className={'text-3xl'}>
            <MyIcon type="icon-bilibili" />
          </Typography.Link>
        </div>
      </div>
      <Row gutter={16}>
        <Col span={18} xs={24} lg={16} xl={17}>
          <Flex vertical={true}>
            <Card variant={'borderless'}>
              <MdPreview id={data?.title} modelValue={data?.introduce}/>
            </Card>
            <Card variant={'borderless'} className={'mt-4'}>
              <PayChoice bisheProjectVO={data ?? {}} />
            </Card>
            <div className={'mt-4 mb-4'}>
              <EssayCommentCard id={id} />
            </div>
          </Flex>
        </Col>
        <Col span={6} xs={24} lg={16} xl={7}>
          <Flex vertical={true}>
            <MyCard title={'📖目录'}>
              <MdCatalog
                className={'text-base'}
                editorId={data?.title ?? ''}
                scrollElement={scrollElement}
                scrollElementOffsetTop={80}
              />
            </MyCard>
            <div className={'mt-4'}>
              <MyCard title={'🔥热门项目'}>
                <CardList
                  data={hotBisheProjects}
                  loading={loading}
                  gutter={{
                    gutter: 16,
                    xs: 1,
                    sm: 1,
                    md: 1,
                    lg: 1,
                    xl: 1,
                    xxl: 1,
                  }}
                />
              </MyCard>
            </div>
            <div className={'mt-4'}>
              <MyCard title={'🚀广告位'}>
                <span>广告位招租~</span>
              </MyCard>
            </div>
          </Flex>
        </Col>
      </Row>
    </>
  );

  return <MyPageContainer content={content} loading={loading} />;
};

export default Detail;
